﻿using System;
using System.Drawing;

namespace KTOP.Core.Domain
{
    public class BoardPlacer
    {
        public Size BoardSize { get; private set; }
        public int ModuleCount { get; private set; }

        private static Size GetBoardSize(int moduleCount)
        {
            var sqrt = (int)Math.Floor(Math.Sqrt(moduleCount));

            if (sqrt * sqrt == moduleCount) return new Size(sqrt, sqrt);
            if (sqrt * (sqrt + 1) >= moduleCount) return new Size(sqrt + 1, sqrt);
            return new Size(sqrt + 1, sqrt + 1);
        }

        public BoardPlacer(int moduleCount)
        {
            ModuleCount = moduleCount;
            BoardSize = GetBoardSize(moduleCount);
        }

        public Point GetBoardPosition(int moduleId)
        {
            if (moduleId >= ModuleCount) 
                throw new ArgumentOutOfRangeException("moduleId");

            var row = moduleId/BoardSize.Width;
            var col = moduleId%BoardSize.Width;

            return new Point(col, row);
        }
    }
}

